package com.cloud.ebookreader.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

public class BlobReaderUtil {
//	private byte[] getImageBytes(BlobData blobData) {
//		BlobstoreService blobstoreService = BlobstoreServiceFactory
//				.getBlobstoreService();
//
//		if (blobData == null) {
//			return null;
//		}
//
//		BlobKey blobKey = new BlobKey(blobData.getKey());
//		if (blobKey == null) {
//			return null;
//		}
//
//		ByteArrayOutputStream out = new ByteArrayOutputStream();
//		long filesize = blobData.getSize();
//		int chunkSize = 1024;
//		long offset = 0;
//		while (offset < filesize) {
//
//			long limit = offset + chunkSize - 1;
//			if (filesize < limit) {
//				limit = filesize - 1;
//			}
//
//			System.out.println("offset=" + offset + " limit=" + limit
//					+ " size=" + filesize);
//
//			byte[] b = null;
//			try {
//				b = blobstoreService.fetchData(blobKey, offset, limit);
//			} catch (Exception e) {
//				// e.printStackTrace();
//				System.out
//						.println("Ga_Service_Image.getImageBytes(): doing workaround");
//				workaround(out, blobKey, offset, filesize);
//				break;
//			}
//			try {
//				if (b != null) {
//					out.write(b);
//				}
//			} catch (IOException e) {
//				e.printStackTrace();
//				return null;
//			}
//
//			offset += chunkSize;
//			if (offset > filesize) {
//				offset = filesize;
//			}
//		}
//
//		byte[] filebytes = out.toByteArray();
//
//		System.out.println("getImageBytes(): filebytes size: "
//				+ filebytes.length + " blobData.size=" + blobData.getSize());
//
//		return filebytes;
//	}

	public void workaround(ByteArrayOutputStream out, BlobKey blobKey,
			long offset, long filesize) {
		BlobstoreService blobstoreService = BlobstoreServiceFactory
				.getBlobstoreService();
		int chunkSize = 1;
		long limit = 0;
		while (offset < filesize) {

			limit = offset + chunkSize - 1;
			if (filesize < limit) {
				limit = filesize;
			}

			System.out.println("offset=" + offset + " limit=" + limit
					+ " size=" + filesize);

			byte[] b = null;
			try {
				b = blobstoreService.fetchData(blobKey, offset, limit);
			} catch (Exception e) {
				// e.printStackTrace();
				return;
			}
			try {
				out.write(b);
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}

			offset += chunkSize;
			if (offset > filesize) {
				offset = filesize;
			}
		}
	}

}
